package com.example.phototest;

import java.io.File;
import java.util.Date;

import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.fangdd.maimaifang.freedom.widget.imagecrop.CropImageActivity;

public class MainActivity extends ActionBarActivity implements OnClickListener
{

    private static String localTempImageFileName = "";
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_MODIFY_FINISH = 7;

    public static final File FILE_LOCAL = new File(Environment.getExternalStorageDirectory(), "test");
    public static final File FILE_PIC_SCREENSHOT = new File(FILE_LOCAL, "images/photo");

    private ImageView imgHeader;

    private BroadcastReceiver receiver1 = new BroadcastReceiver()
    {
        public void onReceive(android.content.Context context, Intent intent)
        {
            Log.e("test", "fadsfadsfsadfs onreceiver");
            Intent intent1 = new Intent(context, TipActivity.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent1);
            Log.e("test", "fadsfadsfsadfs2222222222222 onreceiver");
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter filter = new IntentFilter();
        filter.addAction("test.action");
        registerReceiver(receiver1, filter);

        new Handler().postDelayed(new Runnable()
        {

            @Override
            public void run()
            {
                sendBroadcast(new Intent("test.action"));
                Log.e("test", "post broadcast");

            }
        }, 8000);

        findViewById(R.id.btnAlbum).setOnClickListener(this);
        findViewById(R.id.btnCamera).setOnClickListener(this);

        imgHeader = (ImageView) findViewById(R.id.imageView1);

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test.jpg");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists())
        {
            if (!mediaStorageDir.mkdirs())
            {
                Log.d("MyCameraApp", "failed to create directory");
            }
        }

        // Create a media file name
        String fileDir = mediaStorageDir.getPath();
        Log.i("test", " path url:" + fileDir);

        // receiver = new MyBroadcastReceiver();

        // IntentFilter filter = new IntentFilter("test.action");
        // registerReceiver(receiver1, filter);

    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver1);
    }

    @Override
    public void onClick(View v)
    {
        Intent intent = null;
        switch (v.getId())
        {
        case R.id.btnAlbum:
            intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");

            // intent.setAction(Intent.ACTION_GET_CONTENT);
            // intent.setType("image/*");
            // intent.putExtra(Intent.CATEGORY_OPENABLE, true);

            startActivityForResult(intent, FLAG_CHOOSE_IMG);
            break;
        case R.id.btnCamera:
            String status = Environment.getExternalStorageState();
            if (status.equals(Environment.MEDIA_MOUNTED))
            {
                try
                {
                    File filePath = FILE_PIC_SCREENSHOT;
                    if (!filePath.exists())
                    {
                        filePath.mkdirs();
                    }

                    localTempImageFileName = "";
                    localTempImageFileName = String.valueOf((new Date()).getTime()) + ".png";

                    File f = new File(filePath, localTempImageFileName);

                    // localTempImgDir和localTempImageFileName是自己定义的名字
                    intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                    Uri u = Uri.fromFile(f);
                    intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, u);

                    // Intent intent = new
                    // Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                    startActivityForResult(intent, FLAG_CHOOSE_PHONE);
                }
                catch (ActivityNotFoundException e)
                {
                }
            }
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_OK)
        {
            switch (requestCode)
            {
            case FLAG_CHOOSE_IMG:
                if (data != null)
                {
                    Uri uri = data.getData();
                    if (!TextUtils.isEmpty(uri.getAuthority()))
                    {
                        Cursor cursor = getContentResolver().query(uri, new String[]
                        { MediaStore.Images.Media.DATA }, null, null, null);
                        if (null == cursor)
                        {
                            Toast.makeText(MainActivity.this, "图片没找到", Toast.LENGTH_LONG).show();
                            return;
                        }
                        cursor.moveToFirst();
                        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        cursor.close();

                        Intent intent = new Intent(this, CropImageActivity.class);
                        intent.putExtra("path", path);
                        startActivityForResult(intent, FLAG_MODIFY_FINISH);
                    }
                    else
                    {
                        Intent intent = new Intent(this, CropImageActivity.class);
                        intent.putExtra("path", uri.getPath());
                        startActivityForResult(intent, FLAG_MODIFY_FINISH);
                    }
                }
                break;
            case FLAG_CHOOSE_PHONE:
                File f = new File(FILE_PIC_SCREENSHOT, localTempImageFileName);
                Intent intent = new Intent(this, CropImageActivity.class);
                intent.putExtra("path", f.getAbsolutePath());
                startActivityForResult(intent, FLAG_MODIFY_FINISH);
                break;
            case FLAG_MODIFY_FINISH:
                if (data != null)
                {
                    final String path = data.getStringExtra("path");

                    Bitmap bitmap = BitmapFactory.decodeFile(path);

                    imgHeader.setImageBitmap(bitmap);

                }
                break;
            }
        }
        // private void cropImage(Uri uri)
        // {
        // try
        // {
        // Intent intent = new Intent("com.android.camera.action.CROP");
        // intent.setDataAndType(uri, "image/*");
        // intent.putExtra("crop", "true");
        // File tempFile = new File(FileUtils.getPhotoPath(activity)); //
        // 以时间秒为文件名
        // File temp = new File(FileUtils.getRootDir(activity));// 自已项目 文件夹
        // if (!temp.exists())
        // {
        // temp.mkdir();
        // }
        // intent.putExtra("output", Uri.fromFile(tempFile)); // 专入目标文件
        // intent.putExtra("outputFormat", "JPEG"); // 输入文件格式
        //
        // intent.putExtra("outputX", 150);
        // intent.putExtra("outputY", 150);
        // intent.putExtra("aspectX", 150);
        // intent.putExtra("aspectY", 150);
        // intent.putExtra("scale", true);
        // intent.putExtra("return-data", true);
        // startActivityForResult(intent, RC_IMAGE_CROP);
        // }
        // catch (Exception e)
        // {
        // e.printStackTrace();
        // }
    }

    // void test()
    // {
    // KeyguardManager keyguardManager = (KeyguardManager)
    // getSystemService(Context.KEYGUARD_SERVICE);
    // String lockTag = this.getLocalClassName();
    //
    // KeyguardManager.OnKeyguardExitResult keyguardExitResultListener = new
    // KeyguardManager.OnKeyguardExitResult()
    // {
    // @Override
    // public void onKeyguardExitResult(boolean success)
    // {
    // // TODO Auto-generated method stub
    // if (success)
    // Log.i("test", "successfull to do Keyguard exit");
    // else
    // Log.i("test", "fail to do Keyguard exit");
    // }
    // };
    // keyguardManager.exitKeyguardSecurely(keyguardExitResultListener);
    //
    // KeyguardManager.KeyguardLock keyguardLock =
    // keyguardManager.newKeyguardLock(lockTag);
    // for (int i = 10; i > 0; i--)
    // {
    // try
    // {
    // Thread.sleep(1000);
    // }
    // catch (InterruptedException e)
    // {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // Log.i("test", "We will unlock the screen in " + i + " seconds");
    // }
    // keyguardLock.disableKeyguard();
    // for (int i = 20; i > 0; i--)
    // {
    // try
    // {
    // Thread.sleep(1000);
    // }
    // catch (InterruptedException e)
    // {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // Log.i("test", "We will roll back the state of Keyguard in " + i +
    // " seconds");
    // }
    // long t = System.currentTimeMillis();
    // keyguardLock.reenableKeyguard();
    // Log.i("test", "time:" + (System.currentTimeMillis() - t));
    // }

}
